﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WucCloud.Database;
using WucCloud.Entity;
using WucCloud.Utility;

namespace WucCloud.Application
{
    /// <summary>
    /// 角色服务
    /// </summary>
    public class RoleInfoService :BaseService<RoleInfoEntity>,IDependency
    {
        /// <summary>
        /// 子类构造函数
        /// </summary>
        /// <param name="roleRepository"></param>
        public RoleInfoService(IBaseRepository<RoleInfoEntity> roleRepository, IUnitOfWork unitOfWork)
        {
            base._repository = roleRepository;
            base._unitOfWork = unitOfWork;
        }

        #region 获取数据
        /// <summary>
        /// 通过Id查询
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        public async Task<RoleInfoEntity> FindById(string keyId)
        {
            try
            {
                //通过Id查询角色数据
                var entity = await _repository.FindByIdAsync(keyId);
                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 自定义条件查询
        /// </summary>
        /// <param name="keyvalue">查询条件(编码/角色名称)</param>
        /// <returns></returns>
        public async Task<List<RoleInfoEntity>> GetList(string keyvalue)
        {
            try
            {
                var entity = await _repository.QueryableAsync(t => t.IsEnabled == true && t.IsDeleted == false);
                //条件查询 根据编码/角色名称查询
                if (!string.IsNullOrEmpty(keyvalue))
                {
                    entity = entity.FindAll(t => t.EnCode.Contains(keyvalue) || t.RoleName.Contains(keyvalue));
                }
                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 自定义条件分页查询
        /// </summary>
        /// <param name="keyvalue">查询条件(编码/角色名称)</param>
        /// <param name="page">分页组件类</param>
        /// <returns></returns>
        public async Task<List<RoleInfoEntity>> QueryPagedList(string keyvalue, PageModel page)
        {
            try
            {
                //获取角色分页数据
                var entity = await _repository.SugarQueryable()
                    .Where(t => t.IsEnabled == true && t.IsDeleted == false)
                    .ToOffsetPageAsync(page.PageIndex, page.PageSize);

                //条件查询 根据编码/角色名称查询
                if (!string.IsNullOrEmpty(keyvalue))
                {
                    entity = entity.FindAll(t => t.EnCode.Contains(keyvalue) || t.RoleName.Contains(keyvalue));
                }

                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存数据（新增/编辑）
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <param name="entity">实体信息</param>
        /// <returns></returns>
        public async Task<bool> SaveChange(string keyId, RoleInfoEntity entity)
        {
            try
            {
                //新增
                if (string.IsNullOrEmpty(keyId))
                {
                    #region 数据校验
                    var data = await _repository.AnyAsync(t => t.RoleName == entity.RoleName);
                    if (data == true)
                    {
                        throw new Exception("角色已存在，请重新输入");
                    }
                    //非空校验
                    if (string.IsNullOrEmpty(entity.EnCode) || string.IsNullOrEmpty(entity.RoleName))
                    {
                        throw new Exception("编码/角色名称不可为空");
                    }
                    #endregion

                    //数据初始化
                    entity.KeyId = IDGenerator.CreateNewId();
                    entity.IsEnabled = true;
                    entity.IsDeleted = false;
                    entity.CreateTime = DateTime.Now;
                    entity.CreateUserId = GlobalContext.CurrentUser().KeyId;
                    entity.CreateUserName = GlobalContext.CurrentUser().RealName;

                    return await _repository.InsertAsync(entity);
                }
                //编辑
                else
                {
                    //数据初始化
                    entity.KeyId = keyId;
                    entity.IsEnabled = true;
                    entity.IsDeleted = false;
                    entity.UpdateTime = DateTime.Now;
                    entity.UpdateUserId = GlobalContext.CurrentUser().KeyId;
                    entity.UpdateUserName = GlobalContext.CurrentUser().RealName;

                    return await _repository.UpdateAsync(entity);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        public async Task<bool> Deleteable(string keyId)
        {
            try
            {
                bool result = await _repository.DeleteAsync(keyId);
                if (!result)
                {
                    throw new Exception("删除失败");
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 假删（逻辑删除）
        /// </summary>
        /// <param name="keyId"></param>
        /// <returns></returns>
        public async Task<bool> SoftDeleteable(string keyId)
        {
            try
            {
                var data = await _repository.FindByIdAsync(keyId);
                data.IsEnabled = false;
                data.IsDeleted = true;
                bool result = await _repository.UpdateAsync(data);
                if (!result)
                {
                    throw new Exception("删除失败");
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="keyIds">主键Id集合,以英文逗号分隔</param>
        /// <returns></returns>
        public async Task<bool> BatchDeleteable(string[] keyIds)
        {
            try
            {
                bool result = false;
                //将数组转换为以,分割的字符串
                string Ids = string.Join(",", keyIds);
                foreach (var item in Ids.Split(','))
                {
                    result = await _repository.DeleteAsync(item);
                }
                if (!result)
                {
                    throw new Exception("删除失败");
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }
        #endregion

        #region 拓展

        #endregion
    }
}
